<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon32.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon16.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Data Structure,">










<meta name="description" content="刷题目有段时间了，发现最难得还是模拟。但是也有很多简单问题可以用朴素的空间换时间来大幅加速，看了很多高手的解题报告，发现了这些想法，很典型的是分桶法和树状数组(之后更新了线段树)，做一下总结，希望以后自己能活用在其他问题上。">
<meta name="keywords" content="Data Structure">
<meta property="og:type" content="article">
<meta property="og:title" content="树状数组、分桶法、线段树">
<meta property="og:url" content="http://htelepathh.gitee.io/2018/09/06/树状数组、分桶法、线段树/index.html">
<meta property="og:site_name" content="OUTPUT">
<meta property="og:description" content="刷题目有段时间了，发现最难得还是模拟。但是也有很多简单问题可以用朴素的空间换时间来大幅加速，看了很多高手的解题报告，发现了这些想法，很典型的是分桶法和树状数组(之后更新了线段树)，做一下总结，希望以后自己能活用在其他问题上。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://htelepathh.gitee.io/2018/09/06/树状数组、分桶法、线段树/treearray.jpg">
<meta property="og:updated_time" content="2018-10-07T14:16:47.635Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="树状数组、分桶法、线段树">
<meta name="twitter:description" content="刷题目有段时间了，发现最难得还是模拟。但是也有很多简单问题可以用朴素的空间换时间来大幅加速，看了很多高手的解题报告，发现了这些想法，很典型的是分桶法和树状数组(之后更新了线段树)，做一下总结，希望以后自己能活用在其他问题上。">
<meta name="twitter:image" content="http://htelepathh.gitee.io/2018/09/06/树状数组、分桶法、线段树/treearray.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://htelepathh.gitee.io/2018/09/06/树状数组、分桶法、线段树/">





  <title>树状数组、分桶法、线段树 | OUTPUT</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">OUTPUT</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">HTelepathH's blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-message">
          <a href="/message" rel="section">
            
            留言
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://htelepathh.gitee.io/2018/09/06/树状数组、分桶法、线段树/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HTelepathH">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/MOB.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="OUTPUT">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">树状数组、分桶法、线段树</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-06T23:42:39+08:00">
                2018-09-06
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/algorithm/" itemprop="url" rel="index">
                    <span itemprop="name">algorithm</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>刷题目有段时间了，发现最难得还是模拟。但是也有很多简单问题可以用朴素的空间换时间来大幅加速，看了很多高手的解题报告，发现了这些想法，很典型的是分桶法和树状数组(之后更新了线段树)，做一下总结，希望以后自己能活用在其他问题上。<br><a id="more"></a><br>题目是<a href="https://pintia.cn/problem-sets/994805342720868352/problems/994805417945710592" target="_blank" rel="noopener">PAT1057 Stack</a><br>只是插入和排序找中位数会超时，稍微做变化，有两种方法。</p>
<h2 id="分桶法"><a href="#分桶法" class="headerlink" title="分桶法"></a>分桶法</h2><p>使用数轴hash的方法，求前缀和，在这之前再分块便于搜索，用一个数组记录每块有几个数，块长×块数=总数，时间复杂度O(块长+块数)。<br>类似想法的还有<a href="https://pintia.cn/problem-sets/994805342720868352/problems/994805371602845696" target="_blank" rel="noopener">PAT1095 Cars on Campus</a>使用一天的时间轴time[24×60×60],进门axis[intime]++ 出门axis[outime]— 任意时刻的校园内车的数量只要求前缀和就可以了。<br><figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;string&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;stack&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> total = <span class="number">100000</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> everybk = <span class="number">500</span>;</span><br><span class="line"><span class="keyword">int</span> buckets[total / everybk][everybk];<span class="comment">//number axis</span></span><br><span class="line"><span class="keyword">int</span> cnt[total / everybk] = &#123; <span class="number">0</span> &#125;;<span class="comment">//every bucket count</span></span><br><span class="line"><span class="built_in">stack</span>&lt;<span class="keyword">int</span>&gt;s;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">median</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> count = <span class="number">0</span>,buk,i;</span><br><span class="line">    <span class="keyword">int</span> size = (s.size() % <span class="number">2</span> == <span class="number">0</span>) ? s.size() / <span class="number">2</span>: (s.size()+<span class="number">1</span>) / <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">for</span> (buk=<span class="number">0</span>; buk &lt; total / everybk; buk++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (cnt[buk] + count &gt;= size) <span class="keyword">break</span>;</span><br><span class="line">        count += cnt[buk];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; everybk; i++) &#123;</span><br><span class="line">        count += buckets[buk][i];</span><br><span class="line">        <span class="keyword">if</span> (count &gt;= size) &#123;</span><br><span class="line">            <span class="built_in">cout</span> &lt;&lt; buk * everybk + i &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">"%d"</span>, &amp;n); <span class="keyword">char</span> str[<span class="number">11</span>]; </span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">"%s"</span>, str);</span><br><span class="line">        <span class="keyword">if</span> (str[<span class="number">1</span>] == <span class="string">'o'</span>) &#123; </span><br><span class="line">            <span class="keyword">if</span> (s.empty())<span class="built_in">cout</span> &lt;&lt; <span class="string">"Invalid"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">int</span> temp = s.top();</span><br><span class="line">                buckets[temp / everybk][temp % everybk]--;</span><br><span class="line">                cnt[temp / everybk]--; </span><br><span class="line">                <span class="built_in">cout</span> &lt;&lt; temp &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">                s.pop();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (str[<span class="number">1</span>] == <span class="string">'e'</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span>(s.empty())<span class="built_in">cout</span> &lt;&lt; <span class="string">"Invalid"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">            <span class="keyword">else</span> median();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">int</span> temp;</span><br><span class="line">            <span class="built_in">scanf</span>(<span class="string">"%d"</span>, &amp;temp);</span><br><span class="line">            buckets[temp / everybk][temp % everybk]++;</span><br><span class="line">            cnt[temp / everybk]++;</span><br><span class="line">            s.push(temp);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="树状数组"><a href="#树状数组" class="headerlink" title="树状数组"></a>树状数组</h2><p>树状数组也是一种快速求前缀和的方法，利用lowbit(i){ i &amp; -i;}求出i的二进制表示中最低位的1所表示的数。<br>5 &amp; -5 = 0000 0101 &amp; 1111 1011 = 0000 0001 = 1<br>4 &amp; -4 = 0000 0100 &amp; 1111 1100 = 0000 0100 = 4<br>如此其实可以将任意一个数用lowbit()将其中的1去掉。<br>求前7个前缀和:<br>sum[7]=A[1]+A[2]+A[3]+A[4]+A[5]+A[6]+A[7] ;<br>C[4]=A[1]+A[2]+A[3]+A[4];   C[6]=A[5]+A[6];   C[7]=A[7];<br>sum[7]=C[4]+C[6]+C[7];<br>sum[(111)]=C[(100)]+C[(110)]+C[(111)];</p>
<img src="/2018/09/06/树状数组、分桶法、线段树/treearray.jpg" title="树状数组的例子">
<p>因此自上而下求和，自下而上更新。<br><figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stack&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> maxn = <span class="number">100010</span>;</span><br><span class="line"><span class="keyword">int</span> arr[maxn];</span><br><span class="line"><span class="built_in">stack</span>&lt;<span class="keyword">int</span>&gt;s;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">lowbit</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123; <span class="keyword">return</span> i &amp; -i; &#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">update</span><span class="params">(<span class="keyword">int</span> index, <span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (index &lt;= maxn) &#123;</span><br><span class="line">        arr[index] += val;</span><br><span class="line">        index += lowbit(index);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getsum</span><span class="params">(<span class="keyword">int</span> index)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> result = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (index &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        result += arr[index];</span><br><span class="line">        index -= lowbit(index);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">PeekMedian</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> low = <span class="number">1</span>, high = maxn, mid;</span><br><span class="line">    <span class="keyword">int</span> k = s.size()%<span class="number">2</span> == <span class="number">0</span>? s.size()/<span class="number">2</span>:(s.size()+<span class="number">1</span>)/<span class="number">2</span>;</span><br><span class="line">    <span class="keyword">while</span> (low &lt;= high) &#123;</span><br><span class="line">        mid = (low + high) / <span class="number">2</span>;</span><br><span class="line">        <span class="keyword">if</span> (getsum(mid) &gt;= k)high = mid - <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">else</span> low = mid + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">"%d\n"</span>, low);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n, temp;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">"%d"</span>, &amp;n);</span><br><span class="line">    <span class="keyword">char</span> str[<span class="number">15</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">"%s"</span>, str);</span><br><span class="line">        <span class="keyword">if</span> (str[<span class="number">1</span>] == <span class="string">'u'</span>) &#123;</span><br><span class="line">            <span class="built_in">scanf</span>(<span class="string">"%d"</span>, &amp;temp);</span><br><span class="line">            s.push(temp);</span><br><span class="line">            update(temp, <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (str[<span class="number">1</span>] == <span class="string">'o'</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!s.empty()) &#123;</span><br><span class="line">                update(s.top(), <span class="number">-1</span>);</span><br><span class="line">                <span class="built_in">printf</span>(<span class="string">"%d\n"</span>, s.top());</span><br><span class="line">                s.pop();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="built_in">printf</span>(<span class="string">"Invalid\n"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (!s.empty()) PeekMedian();</span><br><span class="line">            <span class="keyword">else</span> <span class="built_in">printf</span>(<span class="string">"Invalid\n"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="线段树"><a href="#线段树" class="headerlink" title="线段树"></a>线段树</h2><p>线段树在此题可以在logN内求任意区间内的点个数。在此用感觉并不太合适。<br>这里有两种线段树的实现，普通递归的实现和作为学习摘录的zkw线段树(无递归)。</p>
<h3 id="普通递归"><a href="#普通递归" class="headerlink" title="普通递归"></a>普通递归</h3><figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stack&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> maxn = <span class="number">100010</span>;</span><br><span class="line"><span class="keyword">int</span> segtree[<span class="number">4</span>*maxn];</span><br><span class="line"><span class="keyword">int</span> n;</span><br><span class="line"><span class="built_in">stack</span>&lt;<span class="keyword">int</span>&gt;s;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">query</span><span class="params">(<span class="keyword">int</span> l, <span class="keyword">int</span> r, <span class="keyword">int</span> k,<span class="keyword">int</span> kth)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (l == r) <span class="keyword">return</span> l;</span><br><span class="line">    <span class="keyword">int</span> mid = (l + r) &gt;&gt; <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">if</span> (segtree[k &lt;&lt; <span class="number">1</span>] &gt;= kth) <span class="keyword">return</span> query(l, mid, k &lt;&lt; <span class="number">1</span>, kth);</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">return</span> query(mid + <span class="number">1</span>, r, k &lt;&lt; <span class="number">1</span> | <span class="number">1</span>, kth - segtree[k &lt;&lt; <span class="number">1</span>]);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">update</span><span class="params">(<span class="keyword">int</span> l, <span class="keyword">int</span> r, <span class="keyword">int</span> k, <span class="keyword">int</span> index, <span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (l == r) &#123;</span><br><span class="line">        segtree[k] += val;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> mid = (l + r) &gt;&gt; <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">if</span> (index &lt;= mid) update(l, mid, k &lt;&lt; <span class="number">1</span>, index, val);</span><br><span class="line">    <span class="keyword">else</span> update(mid + <span class="number">1</span>, r, k &lt;&lt; <span class="number">1</span> | <span class="number">1</span>, index, val);</span><br><span class="line">    segtree[k] = segtree[k &lt;&lt; <span class="number">1</span>] + segtree[k &lt;&lt; <span class="number">1</span> | <span class="number">1</span>];</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> temp;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">"%d"</span>, &amp;n);</span><br><span class="line">    <span class="keyword">char</span> str[<span class="number">15</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">"%s"</span>, str);</span><br><span class="line">        <span class="keyword">if</span> (str[<span class="number">1</span>] == <span class="string">'u'</span>) &#123;</span><br><span class="line">            <span class="built_in">scanf</span>(<span class="string">"%d"</span>, &amp;temp);</span><br><span class="line">            s.push(temp);</span><br><span class="line">            update(<span class="number">0</span>, maxn, <span class="number">1</span>, temp, <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (str[<span class="number">1</span>] == <span class="string">'o'</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!s.empty()) &#123;</span><br><span class="line">                update(<span class="number">0</span>, maxn, <span class="number">1</span>, s.top(), <span class="number">-1</span>);</span><br><span class="line">                <span class="built_in">printf</span>(<span class="string">"%d\n"</span>, s.top());</span><br><span class="line">                s.pop();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="built_in">printf</span>(<span class="string">"Invalid\n"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (!s.empty()) &#123;</span><br><span class="line">                <span class="keyword">int</span> kth = s.size() % <span class="number">2</span> == <span class="number">0</span> ? s.size() / <span class="number">2</span> : (s.size() + <span class="number">1</span>) / <span class="number">2</span>;</span><br><span class="line">                <span class="built_in">printf</span>(<span class="string">"%d\n"</span>,query(<span class="number">0</span>, maxn, <span class="number">1</span>, kth));</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="built_in">printf</span>(<span class="string">"Invalid\n"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="zkw线段树"><a href="#zkw线段树" class="headerlink" title="zkw线段树"></a>zkw线段树</h3><figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stack&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">int</span> Node;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">zkw_segtree</span>&#123;</span></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    Node *T;</span><br><span class="line">    <span class="keyword">int</span> size;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    zkw_segtree(<span class="keyword">int</span> range)&#123;</span><br><span class="line">        <span class="keyword">for</span> (size = <span class="number">1</span>; size &lt; range + <span class="number">2</span>; size &lt;&lt;= <span class="number">1</span>);</span><br><span class="line">        T = <span class="keyword">new</span> Node[<span class="number">2</span> * size];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; size + size; i++)</span><br><span class="line">            T[i] = <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">Add</span><span class="params">(<span class="keyword">int</span> value, <span class="keyword">int</span> i)</span></span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (i += size; i; i &gt;&gt;= <span class="number">1</span>)</span><br><span class="line">            T[i] += value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">Query</span><span class="params">(<span class="keyword">int</span> s, <span class="keyword">int</span> t)</span></span>&#123;</span><br><span class="line">        <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (s += size - <span class="number">1</span>, t += size + <span class="number">1</span>; s^t ^ <span class="number">1</span>; s &gt;&gt;= <span class="number">1</span>, t &gt;&gt;= <span class="number">1</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span> (~s ^ <span class="number">1</span>) ret += T[s ^ <span class="number">1</span>];</span><br><span class="line">            <span class="keyword">if</span> (t ^ <span class="number">1</span>)  ret += T[t ^ <span class="number">1</span>];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> ret;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">Find_Kth</span><span class="params">(<span class="keyword">int</span> k, <span class="keyword">int</span> root = <span class="number">1</span>)</span></span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (root &lt;&lt; <span class="number">1</span> &lt; size &lt;&lt; <span class="number">1</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span> (T[root &lt;&lt; <span class="number">1</span>] &gt;= k)  root = root &lt;&lt; <span class="number">1</span>;</span><br><span class="line">            <span class="keyword">else</span>&#123;</span><br><span class="line">                k -= T[root &lt;&lt; <span class="number">1</span>];</span><br><span class="line">                root = (root &lt;&lt; <span class="number">1</span>) + <span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> root - size;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    ~zkw_segtree()&#123;</span><br><span class="line">        <span class="keyword">delete</span>[] T;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function">zkw_segtree <span class="title">segtree</span><span class="params">(<span class="number">100000</span>)</span></span>;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> temp, n;</span><br><span class="line">    <span class="built_in">stack</span>&lt;<span class="keyword">int</span>&gt;s;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">"%d"</span>, &amp;n);</span><br><span class="line">    <span class="keyword">char</span> str[<span class="number">15</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">"%s"</span>, str);</span><br><span class="line">        <span class="keyword">if</span> (str[<span class="number">1</span>] == <span class="string">'u'</span>) &#123;</span><br><span class="line">            <span class="built_in">scanf</span>(<span class="string">"%d"</span>, &amp;temp);</span><br><span class="line">            s.push(temp);</span><br><span class="line">            segtree.Add(<span class="number">1</span>, temp);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (str[<span class="number">1</span>] == <span class="string">'o'</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!s.empty()) &#123;</span><br><span class="line">                segtree.Add(<span class="number">-1</span>, s.top());</span><br><span class="line">                <span class="built_in">printf</span>(<span class="string">"%d\n"</span>, s.top());</span><br><span class="line">                s.pop();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> <span class="built_in">printf</span>(<span class="string">"Invalid\n"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (!s.empty()) </span><br><span class="line">                <span class="built_in">printf</span>(<span class="string">"%d\n"</span>,segtree.Find_Kth((s.size() + <span class="number">1</span>) / <span class="number">2</span>));</span><br><span class="line">            <span class="keyword">else</span> <span class="built_in">printf</span>(<span class="string">"Invalid\n"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Data-Structure/" rel="tag"># Data Structure</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/03/常用的排序算法/" rel="next" title="常用的排序算法">
                <i class="fa fa-chevron-left"></i> 常用的排序算法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/14/Viewing-matrices/" rel="prev" title="Viewing matrices">
                Viewing matrices <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/MOB.jpg" alt="HTelepathH">
            
              <p class="site-author-name" itemprop="name">HTelepathH</p>
              <p class="site-description motion-element" itemprop="description">Learning by doing.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="99088577@qq.com" target="_blank" title="Mail">
                      Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/htelepathh" target="_blank" title="Gitee">
                      Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/htlpt" target="_blank" title="GitHub">
                      GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/6207125886" target="_blank" title="微博">
                      微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/huang-he-tu" target="_blank" title="知乎">
                      知乎</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#分桶法"><span class="nav-number">1.</span> <span class="nav-text">分桶法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#树状数组"><span class="nav-number">2.</span> <span class="nav-text">树状数组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#线段树"><span class="nav-number">3.</span> <span class="nav-text">线段树</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#普通递归"><span class="nav-number">3.1.</span> <span class="nav-text">普通递归</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#zkw线段树"><span class="nav-number">3.2.</span> <span class="nav-text">zkw线段树</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-angle-double-left"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HTelepathH</span>

  
</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  
  


  

  

</body>
</html>
